package cn.wfu.rlrjds.app.user.service.ipml;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.wfu.rlrjds.app.bean.UserSearch;
import cn.wfu.rlrjds.app.repaire.dao.IRepaireDao;
import cn.wfu.rlrjds.app.repairman.dao.IRepairmanDao;
import cn.wfu.rlrjds.app.repairman.domain.Repaireman;
import cn.wfu.rlrjds.app.user.dao.IUserDao;
import cn.wfu.rlrjds.app.user.domain.User;
import cn.wfu.rlrjds.app.user.service.IUserService;
import cn.wfu.rlrjds.jersey.api.IMUserAPI;
import cn.wfu.rlrjds.jersey.comm.body.IMUserBody;
import cn.wfu.rlrjds.jersey.comm.body.ModifyNicknameBody;
import cn.wfu.rlrjds.jersey.comm.body.ResetPasswordBody;
import cn.wfu.rlrjds.jersey.comm.wrapper.ResponseWrapper;
import cn.wfu.rlrjds.utils.EasemobRestAPIFactoryUtils;
import cn.wfu.rlrjds.utils.MD5Util;

@Service(value = "userService")
@Transactional(readOnly = true)
public class UserServiceIpml implements IUserService {
	@Resource
	private IUserDao userDao;
	@Resource
	private IRepairmanDao repairmanDao;
	@Autowired
	private IRepaireDao repaireDao;

	/**
	 * 用户注册
	 * 
	 * @throws UserEcxeption
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED)
	public void regist(User form) throws UserEcxeption {
		// TODO Auto-generated method stub
		//
		User user = userDao.findById(form.getUid());
		Repaireman _repairman = this.repairmanDao.findById(form.getUid());
		if (null == user && _repairman == null) {
			// 创建IMUSer用户
			IMUserAPI imUserAPI = EasemobRestAPIFactoryUtils.getIMUserAPI();
			IMUserBody userBody = new IMUserBody(form.getUid(),
					form.getPassword(), form.getName());
			ResponseWrapper responseWrapper = (ResponseWrapper) imUserAPI
					.createNewIMUserSingle(userBody);
			// 保存用户
			if (200 == responseWrapper.getResponseStatus()) {
				// 使用md5进行密码的加密
				String password = MD5Util.getkeyBeanofStr(form.getPassword());
				form.setPassword(password);
				form.setRegist_time(new Date());

				userDao.save(form);
			} else {
				throw new RuntimeException("环信添加用户失败");
			}
		} else {
			throw new UserEcxeption("用户名已经存在");
		}

	}

	/**
	 * 通过id查找用户
	 * 
	 * @throws UserEcxeption
	 * 
	 */
	@Override
	public User findUserById(String uid) throws UserEcxeption {
		// TODO Auto-generated method stub
		User user = userDao.findById(uid);
		if (user == null) {
			throw new UserEcxeption("用户名不存在");
		}
		return user;
	}

	/**
	 * 查找所有用户
	 */
	@Override
	public List<User> findAllUser(UserSearch user) {
		// TODO Auto-generated method stub
		return this.userDao.selectList("findListBy", user);
	}

	/**
	 * 删除用户
	 * 
	 * @throws UserEcxeption
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"UserEcxeption", "RuntimeException" })
	public void deleteUsers(String[] ids) throws UserEcxeption {
		// TODO Auto-generated method stub
		// 删除环信IMUser用户
		IMUserAPI imUserAPI = EasemobRestAPIFactoryUtils.getIMUserAPI();
		for (int i = 0; i < ids.length; i++) {
			// 删除本地数据库
			this.userDao.deleteByIdByUpdateDeleteStatus(ids[i]);
			ResponseWrapper responseWrapper = (ResponseWrapper) imUserAPI
					.deleteIMUserByUserName(ids[i]);
			if (200 != responseWrapper.getResponseStatus()) {
				throw new UserEcxeption("环信IMuser插入失败");
			}
		}
	}

	/**
	 * 修改用户资料
	 * 
	 * @return 修改后的个人资料
	 * @throws UserEcxeption
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"UserEcxeption", "RuntimeException" })
	public User updateUserInfo(User form, String saveDir) throws UserEcxeption {
		// TODO Auto-generated method stub
		User user = this.userDao.findById(form.getUid());
		if (StringUtils.isNotBlank(form.getAvatarUrl())) {
			if (StringUtils.isNotBlank(user.getAvatarUrl())
					&& !user.getAvatarUrl().equals(form.getAvatarUrl())) {
				String AvatarUrl = user.getAvatarUrl();
				File file = new File(saveDir, AvatarUrl);
				if (file.exists()) {
					file.delete();
				}
			}
		}
		// 修改用户数据库信息
		if (!user.equals(form)) {
			this.userDao.updateUserInfo(form);
		} else {
			return user;
		}
		// 修改维修记录用户信息
		// 修改环信端昵称
		if (!form.getName().equals(user.getName())) {
			IMUserAPI imUserAPI = EasemobRestAPIFactoryUtils.getIMUserAPI();
			ModifyNicknameBody modifyNicknameBody = new ModifyNicknameBody(
					form.getName());
			ResponseWrapper responseWrapper = (ResponseWrapper) imUserAPI
					.modifyIMUserNickNameWithAdminToken(form.getUid(),
							modifyNicknameBody);
			if (StringUtils.isNotBlank(form.getName())
					&& !form.getName().equals(user.getName())) {
				this.repaireDao.updateRepaireName(form);
			}
			if (200 == responseWrapper.getResponseStatus()) {
				return this.userDao.findById(form.getUid());
			} else {
				throw new UserEcxeption("环信端密码修改错误");
			}
		} else {
			return this.userDao.findById(form.getUid());
		}
	}

	/**
	 * 修改用户密码
	 * 
	 * @throws UserEcxeption
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"UserEcxeption", "RuntimeException" })
	public void updateUserPassword(User form, String newpass)
			throws UserEcxeption {
		// TODO Auto-generated method stub
		if (StringUtils.isBlank(newpass)) {
			throw new RuntimeException("新密码不能为空");
		}
		User user = this.userDao.findById(form.getUid());
		if (user != null) {
			if (!user.getPassword().equals(
					MD5Util.getkeyBeanofStr(form.getPassword()))) {
				throw new UserEcxeption("输入的旧密码不正确");
			} else {
				// 设置新密码
				form.setPassword(MD5Util.getkeyBeanofStr(newpass));
				// 修改环信端密码
				IMUserAPI imUserAPI = EasemobRestAPIFactoryUtils.getIMUserAPI();
				ResetPasswordBody resetPasswordBody = new ResetPasswordBody(
						newpass);
				this.userDao.updateUserPassword(form);
				ResponseWrapper responseWrapper = (ResponseWrapper) imUserAPI
						.modifyIMUserPasswordWithAdminToken(form.getUid(),
								resetPasswordBody);
				if (200 != responseWrapper.getResponseStatus()) {
					throw new UserEcxeption("环信端修改数据失败");
				}
			}
		} else {
			throw new RuntimeException("查找的用户为空");
		}

	}

	/**
	 * 修改用户密码（不需要MD5验证）
	 * 
	 * @throws UserEcxeption
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"UserEcxeption", "RuntimeException" })
	public void updatePasswordNoValidate(User form) throws UserEcxeption {
		// TODO Auto-generated method stub
		User user = this.userDao.findById(form.getUid());

		if (!user.getPassword().equals(form.getPassword())) {
			form.setPassword(MD5Util.getkeyBeanofStr(form.getPassword()));
			// 修改环信端密码
			IMUserAPI imUserAPI = EasemobRestAPIFactoryUtils.getIMUserAPI();
			ResetPasswordBody resetPasswordBody = new ResetPasswordBody(
					form.getPassword());
			this.userDao.updateUserPassword(form);
			ResponseWrapper responseWrapper = (ResponseWrapper) imUserAPI
					.modifyIMUserPasswordWithAdminToken(form.getUid(),
							resetPasswordBody);
			if (200 != responseWrapper.getResponseStatus()) {
				throw new UserEcxeption("环信端修改数据失败");
			}
		}
	}
}
